<?php

namespace App\Console\Commands;

use App\Models\AdrewardDetail;
use Illuminate\Console\Command;

class RewardMigrateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reward:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Reward migrate';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $totalCount = AdrewardDetail::count();
        $this->info(sprintf("=== Total Users: %s", $totalCount));

        $chunkSize = 5000;
        $processedCount = 0;

        AdrewardDetail::query()
            ->select(['id', 'user_id', 'adtype_id', 'admodel_id', 'displayed_at'])
            ->chunk($chunkSize, function ($ads) use ($totalCount, &$processedCount, $chunkSize) {
                foreach ($ads as $ad) {
                    $ad->update([
                        'hashid' => AdrewardDetail::hashid($ad->toArray()),
                    ]);
                }
                $processedCount += count($ads);
                $this->info(sprintf("Processed %d / %d ads...", $processedCount, $totalCount));
            });

        $this->info("== Done");

        return 0;
    }
}
